﻿using System;
using System.Collections.Generic;
using System.Linq;
using Peak.Core;

namespace Peak.Web.Controllers.Models
{
  public class TaskModel : ModelBase
  {
    public int TaskId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public TimeSpan RemainingEffort { get; set; }
    public TaskStatus Status { get; set; }
    public string AssignedTo { get; set; }
    public string Category { get; set; }
    public int SprintStoryId { get; set; }
    public string Created { get; set; }
    public string StartDate { get; set; }
    public string EndDate { get; set; }

    public TaskModel() : base(()=>new TaskModelValidator())
    {
      Status = TaskStatus.ToDo;      
    }

    public TaskModel(int sprintStoryId)
      : this()
    {      
      SprintStoryId = sprintStoryId;
    }

    public TaskModel(Task task): this(task.SprintStory.Id)
    {
      TaskId = task.Id;
      Description = task.Description;
      Name = task.Name;
      Category = task.Category;
      RemainingEffort = task.RemainingEffort;
      Status = task.Status;      
      if (task.AssignedTo != null)
        AssignedTo = task.AssignedTo.UserName;
      Created = task.CreatedBy + "(" + task.Created.ToShortDateString() + ")";
      if (task.StartDate != null)
      {
        StartDate = task.StartDate.Value.ToShortDateString();
      }
      if (task.EndDate != null)
      {
        EndDate = task.EndDate.Value.ToShortDateString();
      }
    }

    public void UpdateEdit(Task dbTask, IList<User> users)
    {
      dbTask.Name = Name;
      dbTask.Description = Description;
      dbTask.Category = Category;      
      dbTask.RemainingEffort = RemainingEffort;
      dbTask.Status = Status;
      if (AssignedTo == null)
        dbTask.AssignedTo = null;
      else
        dbTask.AssignedTo = users.First(f => f.UserName.ToLower() == AssignedTo.ToLower());
    }

    public void UpdateNew(Task dbTask, IList<User> users)
    {
      UpdateEdit(dbTask,users);      
    }
  }
}
